#!/usr/bin/env python3
"""
数据库性能优化迁移脚本
添加必要的数据库索引以提高查询性能
"""

import sqlite3
import os
from pathlib import Path

def add_indexes():
    """添加数据库索引"""
    db_path = Path(__file__).parent / "app.db"
    
    if not db_path.exists():
        print("数据库文件不存在，跳过索引创建")
        return
    
    conn = sqlite3.connect(str(db_path))
    cursor = conn.cursor()
    
    # 要添加的索引列表
    indexes = [
        # 用户表索引
        "CREATE INDEX IF NOT EXISTS idx_users_created_at ON users(created_at)",
        "CREATE INDEX IF NOT EXISTS idx_users_last_login ON users(last_login)",
        
        # 解析任务表索引
        "CREATE INDEX IF NOT EXISTS idx_parse_tasks_user_id ON parse_tasks(user_id)",
        "CREATE INDEX IF NOT EXISTS idx_parse_tasks_status ON parse_tasks(status)",
        "CREATE INDEX IF NOT EXISTS idx_parse_tasks_created_at ON parse_tasks(created_at)",
        "CREATE INDEX IF NOT EXISTS idx_parse_tasks_execution_mode ON parse_tasks(execution_mode)",
        "CREATE INDEX IF NOT EXISTS idx_parse_tasks_priority ON parse_tasks(priority)",
        
        # 解析结果表索引
        "CREATE INDEX IF NOT EXISTS idx_parse_results_task_id ON parse_results(task_id)",
        "CREATE INDEX IF NOT EXISTS idx_parse_results_content_type ON parse_results(content_type)",
        
        # 切片任务表索引
        "CREATE INDEX IF NOT EXISTS idx_slice_tasks_parse_task_id ON slice_tasks(parse_task_id)",
        "CREATE INDEX IF NOT EXISTS idx_slice_tasks_status ON slice_tasks(status)",
        "CREATE INDEX IF NOT EXISTS idx_slice_tasks_created_at ON slice_tasks(created_at)",
        
        # 切片块表索引
        "CREATE INDEX IF NOT EXISTS idx_slice_chunks_slice_task_id ON slice_chunks(slice_task_id)",
        
        # API日志表索引
        "CREATE INDEX IF NOT EXISTS idx_api_logs_user_id ON api_logs(user_id)",
        "CREATE INDEX IF NOT EXISTS idx_api_logs_created_at ON api_logs(created_at)",
        "CREATE INDEX IF NOT EXISTS idx_api_logs_status_code ON api_logs(status_code)",
        "CREATE INDEX IF NOT EXISTS idx_api_logs_endpoint ON api_logs(endpoint)",
        
        # 系统监控数据表索引
        "CREATE INDEX IF NOT EXISTS idx_system_metrics_timestamp ON system_metrics(timestamp)",
        
        # 系统配置表索引
        "CREATE INDEX IF NOT EXISTS idx_system_configs_config_key ON system_configs(config_key)",
    ]
    
    print("开始创建数据库索引...")
    
    for index_sql in indexes:
        try:
            cursor.execute(index_sql)
            print(f"✓ 创建索引: {index_sql}")
        except sqlite3.Error as e:
            print(f"✗ 创建索引失败: {index_sql}")
            print(f"  错误: {e}")
    
    # 提交更改
    conn.commit()
    conn.close()
    
    print("数据库索引创建完成")

if __name__ == "__main__":
    add_indexes()